<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-perm="'dept:list'" v-on:click="getDepartments">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <!--
      @selection-change="selsChange" ： 勾选时触发，会将已选择的元素传递给我们
      和 type="selection" 一起连用
      -->
    <el-table :data="departments" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange"
              style="width: 100%;">
      <!--选择框-->
      <el-table-column type="selection" width="55">
      </el-table-column>
      <!--序号列-->
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="160" sortable>
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="160" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="160" :formatter="formatSex" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state == 0" style="color: #42d885">启用</span>
          <span v-else-if="scope.row.state == -1" style="color: #e64242">禁用</span>
          <span v-else style="color: #8c939d">未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="管理员" width="160" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="160" sortable>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!-- :disabled="this.sels.length===0" 控制按钮启用、禁用 -->
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :current-page="currentPage"
          :total="total"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑和修改界面-->
    <!--
         dialogTitle : 模态框标题
        :visible.sync : 控制模态框窗口是否打开
        :model="editForm" 表单数据对象，绑定模型层的部门数据
        :rules="editFormRules" 校验规则
         ref="editForm"  ref引用，相当于给表单取了个id，后期使用该ref引用就可以获取到表单
        
        :close-on-click-modal 控制右上角x
        :model="editForm" 双向绑定表单数据
        :rules 校验规则
        ref 表单别名
    -->
    <el-dialog :title="dialogTitle" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="-1">禁用</el-radio>
            <el-radio class="radio" :label="0">正常</el-radio>
          </el-radio-group>
        </el-form-item>
              <!--
                v-for="item in employees" 遍历员工信息，item：当前员工对象
                :key="item.id" 唯一标识，一般用id即可
                :label="item.username" 选中后展示的内容
                :value="item" 选择后提交的数据是什么，如果是对象，必须配合value-key="id"
                -->
        <el-form-item label="管理员">
          <template>
            <el-select v-model="editForm.manager" value-key="id" placeholder="请选择">
              <el-option
                  v-for="item in employees"
                  :key="item.id"
                  :label="item.username"
                  :value="item">
                <span style="float: left">{{ item.username }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="上级部门" prop="parent">
          <el-cascader v-model="editForm.parent"
              :options="deptTree"
              :props="{
                checkStrictly: true,
                value:'id',
                label:'name'
              }">
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import {
  getDepartmentListPage,
  removeDepartment,
  batchRemoveDepartment,
  editDepartment,
  addDepartment
} from '../../api/api';

export default {
  data() {
    return {
      filters: { //查询参数
        keyword: ''
      },
      deptTree:[], //部门树
      employees: [], //管理员数据
      dialogTitle: "",//模态框标题
      departments: [], //列表部门数据
      total: 0,        //总条数
      pageSize: 5,     //每页显示条数
      currentPage: 1,   //当前页
      listLoading: false,
      sels: [],//列表选中列

      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      editFormRules: { //部门的校验规则
        name: [ //校验部门名称
          {required: true, message: '请输入名称', trigger: 'blur'}//blur失去焦点,trigger触发
        ]
      },
      //编辑界面和新增界面的数据
      editForm: {
        id: null,
        sn: '',
        name: '',
        dirPath:'',
        state: 0,
        manager: null,
        parent: null
      },
    }
  },
  methods: {

    //状态
    formatSex: function (row, column) {
      return row.state == 0 ? '正常' : row.state == -1 ? '禁用' : '未知';
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getDepartments();
    },
    //获取部门列表
    getDepartments() {
      //1.准备分页参数：当前页，每页显示条数
      let para = {
        currentPage: this.currentPage, //1
        pageSize: this.pageSize,       //5
        keyword: this.filters.keyword
      };
      //忙等框
      this.listLoading = true;//开启忙等框
      //发送axios请求
      this.$http.post("/dept", para)
          .then(res => {
            console.log(res)
            this.departments = res.data.rows
            this.total = res.data.totals
            this.listLoading = false;
          }).catch(res => {
        this.$message({
          message: '服务器忙，请稍后重试！',
          type: 'error'
        });
      })
    },
    search() {
      this.currentPage = 1
      this.getDepartments();
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => { //点击确认
        this.listLoading = true;
        //NProgress.start();
        this.$http.delete("/dept/" + row.id)
            .then(res => {
              if (res.data.success) {
                this.$message({
                  message: res.data.msg,
                  type: 'success'
                });
                this.listLoading = false;//关闭忙等框
              } else {
                this.$message({
                  message: res.data.msg,
                  type: 'error'
                });
              }
            }).catch(res => {
          this.$message({
            message: '服务器繁忙，请稍后重试！',
            type: 'error'
          });
        })
        //刷新
        this.search();
        //this.getDepartments();
      }).catch(() => {//点击取消

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {//row 是保存在内存中的
      console.log(row);
      this.dialogTitle = "编辑";//设置模态框标题
      this.editFormVisible = true;//显示模态框
      //this.$refs['editForm'].resetFields(); //清除校验规则
      //克隆对象
      this.editForm = Object.assign({}, row);//this.editForm = row不能用，会出现编辑了没保存却改了值
      this.getDeptTree();
      //console.log(row) //dirPath:"/51/52/53"
      if(this.editForm.dirPath){
        let arr = this.editForm.dirPath.split("/"); //['', '51', '52', '53']
        let arrPath = []
        if(arr.length <= 2){
          arrPath.push(parseInt(arr[1]));
        }else{
          for(let i = 1;i <= arr.length-2;i++){
            arrPath.push(parseInt(arr[i]));//解析为数字的数组
          }
        }
        this.editForm.parent=arrPath;
      }
    },
    //显示新增界面
    handleAdd: function () {
      this.dialogTitle = "新增";//设置模态框标题
      this.editFormVisible = true;//新增与编辑显示同一个模态框
      //this.$refs['editForm'].resetFields(); //清除校验规则
      this.editForm = { //重置表单， 方案：editForm数据双向绑定
        id: null,//清空id
        sn: '',
        name: '',
        dirPath: '',
        state: 0,
        manager: null,
        parent: null
      };
      this.getDeptTree();//查询部门树
    },
    //编辑和新增 框中的 提交按钮
    editSubmit: function () {
      //this.$refs 获取所有的ref引用
      //this.$refs.editForm 获取ref引用叫editForm的表单
      //validate 执行校验(提交时校验，万一没点校验框就不会失去焦点，校验失效)
      this.$refs.editForm.validate((valid) => {
        if (valid) {//校验通过
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true; //按钮忙等
            //NProgress.start();
            //id:新增时为null，修改时id有值
            let para = Object.assign({}, this.editForm);
            //要对parent做一个处理(把数组 转为 对象)
            if(para.parent){
              para.parent = {"id":para.parent[para.parent.length-1]}
            }

            this.$http.put("/dept",para)
                .then(res=>{
                  this.editLoading = false;//关闭按钮忙等
                  this.editFormVisible = false;//关闭模态框
                  if (res.data.success) {
                    this.$message({
                      message: res.data.msg,
                      type: 'success'
                    });
                    this.search();//刷新界面，并跳转到第一页
                  } else { //失败时
                    this.editLoading = false;//只关闭按钮忙等，不关闭模态框，不然模态框里填的数据会消失
                    this.$message({
                      message: res.data.msg,
                      type: 'error'
                    });
                  }
                })
                .catch(res=>{
                  this.editLoading = false;  //关闭按钮忙等
                  this.$message({
                    message: "系统异常",
                    type: 'error'
                  });
                })
          });
        }
      });
    },

    selsChange: function (sels) { //选择框改变
      //console.log(sels)
      this.sels = sels;//赋值
    },
    //批量删除
    batchRemove: function () {
      //this.sels [{id:xx,name:xx,...},{id:xx,name:xx,...}...]
      //获取已选择的数据的id们
      var ids = this.sels.map(item => item.id)//.toString();
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => { //点击确认删除
        this.$http.patch("/dept", ids)
            .then(res => {
              //console.log(res)
              if (res.data.success) {
                this.$message({
                  message: res.data.msg,
                  type: 'success'
                });
              } else {
                this.$message({
                  message: res.data.msg,
                  type: 'error'
                });
              }
              this.search();
            }).catch(res => {
              this.$message({
                message: "服务器正忙，请稍后重试",
                type: 'error'
              })
            })
      }).catch(() => { //取消删除

      });
    },
    getEmployees(){ //获取员工
      //发送请求
      this.$http.get("/emp")
          .then(res => {
            //console.log(res)
            this.employees = res.data
          }).catch(res => {
      })
    },
    getDeptTree(){
      this.$http.get("/dept/tree")
          .then(res => {
            this.deptTree = res.data
            //console.log(this.deptTree)
          }).catch(res => {
      })
    }
  },
  mounted() { //页面加载完成
    this.getDepartments();
    this.getEmployees();
  }
}

</script>

<style scoped>

</style>